package offer;

/**
 * @Auther: wangliuyang
 * @Date: 2021/4/25 21:04
 * @Description: 剑指 Offer 55 - II. 平衡二叉树
 */
public class Offer_55_2 {
    public boolean isBalanced1(TreeNode root) {
        if (root == null) {
            return true;
        }
        return isBalanced(root) == -1 ? false : true;
    }
    /**
     * Desc:返回节点树最大高度同时判断高度差，当不平衡时直接返回-1，剪纸算法，不平衡直接返回高度-1
     * @param root
     * @return {@link int}
     * @author wangliuyang
     * @date
     */
    public int isBalanced(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = isBalanced(root.left);
        int rigth = isBalanced(root.right);
        if (left== -1) {
            return -1;
        }
        if (rigth == -1) {
            return -1;
        }
        return Math.abs(left - rigth) < 2 ? Math.max(left , rigth) + 1 : -1 ;
    }
}
